#include "logindialog.h"
#include "ui_logindialog.h"

#include<QSqlQuery>
#include<QCompleter>
#include<QString>
#include<QMessageBox>
#include<QTimer>
#include<QCryptographicHash>
#include<QBitmap>
#include<QPainter>
#include<QDebug>


LoginDialog::LoginDialog(QWidget *parent) :
    QDialog(parent, Qt::FramelessWindowHint),
    ui(new Ui::LoginDialog)
{
    ui->setupUi(this);
    //初始化界面
    initializeStyleSheet();
    //初始化账号信息（要之前保存过账号、密码才能初始化）
    initializeAccountInformation();
    ui->forgetPasswordLabel->installEventFilter(this);

    //根据账号的输入补全密码
    connect(ui->usernameTextLineEdit, &QLineEdit::textChanged,
            this, [&](QString content){
        if(m_pastUserName.size() > content.size() && m_isMD5Password == true){
            ui->passwordTextLineEdit->clear();
        }
        qDebug()<<"输入的账号:"<<content;
        m_isMD5Password = false;
        auto iter = m_loginInformation.find(content);
        if(iter != m_loginInformation.end()){
            if(iter.value().size() != 0){
                ui->passwordTextLineEdit->setText(iter.value());
                m_isMD5Password = true;
                qDebug()<<"填充的密码:"<<(*iter);
            }else{
                qDebug()<<"没有填充密码";
            }
        }
        m_pastUserName = content;

    });
    //根据密码的输入，变更m_isMD5Password
    connect(ui->passwordTextLineEdit, &QLineEdit::textChanged,
            this, [&](QString content){
        if(m_isMD5Password == true){
            m_isMD5Password = false;
        }
    });
    //登陆操作
    connect(ui->loginPushButton, &QAbstractButton::clicked,
            this, &LoginDialog::loginOperator);
    //退出登陆
    connect(ui->exitPushButton, &QAbstractButton::clicked, this, [=](){
        exit(0);
    });

}

LoginDialog::~LoginDialog()
{
    delete ui;
}

void LoginDialog::initializeStyleSheet()
{
    this->setStyleSheet("QDialog#LoginDialog{background-color:lightGray;color:balck}");
    //登陆按钮
    ui->loginPushButton->setStyleSheet("background-color: rgb(246, 195, 86);font-size:20px;color:white");
    //退出按钮
    ui->exitPushButton->setStyleSheet("background-color: rgb(116, 135, 242);font-size:20px;color:white");

    //棱角圆滑
     QBitmap bmp(this->size());
     bmp.fill();
     QPainter p(&bmp);
     p.setPen(Qt::NoPen);
     p.setBrush(Qt::black);
     p.setPen(Qt::transparent);//表示RGBA值为(0,0,0,0)的透明色。
     p.setRenderHint(QPainter::Antialiasing); // 反锯齿;
     p.drawRoundedRect(bmp.rect(), 20, 20);
     setMask(bmp);
     //密码为秘文输入
     ui->passwordTextLineEdit->setEchoMode(QLineEdit::Password);

     ui->usernameTextLineEdit->setStyleSheet("color:black");
     ui->usernamseTitleLabel->setStyleSheet("color:black");
     ui->passwordTextLineEdit->setStyleSheet("color:black");
     ui->passwordTitleLabel->setStyleSheet("color:black");
     ui->forgetPasswordLabel->setStyleSheet("color:black");
     ui->saveLoginStatusCheckBox->setStyleSheet("color:black");
     ui->savePasswordCheckBox->setStyleSheet("color:black");
     ui->titleLabel->setStyleSheet("color:black");
     ui->authorLabel->setStyleSheet("color:black");

     QPixmap labelBackgroundImage(":/Image/background.png");
     labelBackgroundImage.scaled(ui->backgroundLabel->size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
     ui->backgroundLabel->setScaledContents(true);
     ui->backgroundLabel->setPixmap(labelBackgroundImage);
}

void LoginDialog::initializeAccountInformation()
{
    QSqlQuery query(QSqlDatabase::database("connection1"));
    query.exec("SELECT username,password FROM UserSaveInformation");
    QStringList usernameList;
    while(query.next()){
        usernameList<<query.value(0).toString();
        //记录账号和密码组合
        m_loginInformation[query.value(0).toString()] = query.value(1).toString();
    }
    //填充到用户名中
    QCompleter *completer = new QCompleter(usernameList, this);
    completer->setCaseSensitivity(Qt::CaseInsensitive);
    ui->usernameTextLineEdit->setCompleter(completer);

    for(QMap<QString, QString>::iterator iter = m_loginInformation.begin();iter != m_loginInformation.end();iter++){
        qDebug()<<"账号："<<iter.key()<<"密码："<<iter.value();
    }
}

void LoginDialog::loginOperator()
{
    //移除空字符后得到账号和密码
    QString username = ui->usernameTextLineEdit->text().remove(QChar('\040'), Qt::CaseInsensitive);
    QString password = ui->passwordTextLineEdit->text().remove(QChar('\040'), Qt::CaseInsensitive);

    //判断数据的合法性
    if(username.size() == 0){
        QMessageBox* infoBox = new QMessageBox(QMessageBox::Critical, tr("信息提示"),tr("请先输入账号再登陆，谢谢！"));
        QTimer::singleShot(1500, infoBox,&QMessageBox::accept);
        infoBox->show();
        ui->usernameTextLineEdit->setFocus();
    }else if(password.size() == 0){
        QMessageBox* infoBox = new QMessageBox(QMessageBox::Critical,  tr("信息提示"),tr("请先输入密码再登陆，谢谢！"));
        QTimer::singleShot(1500, infoBox, &QMessageBox::accept);
        infoBox->show();
        ui->passwordTextLineEdit->setFocus();
    }else{
        if(m_isMD5Password == false){//转换为md5码
            QCryptographicHash passwordHash(QCryptographicHash::Md5);
            QByteArray passwordMD5;
            passwordMD5.append(password.toUtf8());
            passwordHash.addData(passwordMD5);
            password = passwordHash.result().toHex();
        }
        qDebug()<<"password:"<<password;

        //检查密码是否正确
        QSqlQuery query(QSqlDatabase::database("connection1"));
        query.exec(QString("SELECT password FROM UserInformation WHERE username = '%1'").arg(username));
        QStringList usernameList;
        while(query.next()){
            qDebug()<<"查询到的密码:"<<query.value(0).toString();
           if(password == query.value(0).toString()){
               //保存用户名、密码、account
               if(ui->savePasswordCheckBox->isChecked()){
                   //更新本地数据库
                   query.exec(QString("INSERT OR REPLACE INTO UserSaveInformation(username,password) VALUES (\'%1\', \'%2\')").arg(username, password));
               }else if(ui->saveLoginStatusCheckBox->isChecked()){//保存用户名
                   query.exec(QString("INSERT OR REPLACE INTO UserSaveInformation(username) VALUES (\'%1\')").arg(username));
               }

               emit show2MainWidget();
               this->close();
               return;
           }
        }
        QMessageBox* infoBox = new QMessageBox(QMessageBox::Critical,  tr("信息提示"),tr("账号不存在或密码错误，请重新输入！"));
        QTimer::singleShot(1500, infoBox, &QMessageBox::accept);
        infoBox->show();
        ui->passwordTextLineEdit->setFocus();
    }
}

bool LoginDialog::eventFilter(QObject *obj, QEvent *event)
{
    if(obj == ui->forgetPasswordLabel){
        if(event->type() == QEvent::MouseButtonPress){
                    QMouseEvent* mouseEvent = static_cast<QMouseEvent*>(event);
                    if(mouseEvent->button() == Qt::LeftButton){
                        emit show2RegisterDialog();
                        return true;
                    }else return false;
                }else return false;
    }
    else{
        return LoginDialog::eventFilter(obj, event);
    }
}

void LoginDialog::keyPressEvent(QKeyEvent *event)
{
    if (event->key() == Qt::Key_Return) {
            loginOperator();
     }else{
        //空操作
    }
}
